package MyLinkedQuene;
//队列(链)
public class MyLinkedQuene {

    class Node {
        int val;
        Node next;
        public Node(int val) {
            this.val = val;
        }
    }

    Node head;
    Node last;

    //入队
    public void offer(int val) {
        Node newNode = new Node(val);
        if (isEmpty()) {
            head = last = newNode;
            return;
        }
        last.next = newNode;
        last = last.next;
    }

    //出队
    public int poll() {
        if (isEmpty()) {
            throw new RuntimeException("空队列");
        }
        int ret = head.val;
        head = head.next;
        if (head == null) {  //如果只有一个节点，那就还要更新last
            last = null;
        }
        return ret;
    }

    public boolean isEmpty() {
        return head == last;
    }

    //查看对头元素
    public int peek() {
        if (isEmpty()) {
            throw new RuntimeException("空队列");
        }
        return head.val;
    }

    public int size() {
        int count = 0;
        Node tmp = head;
        while (tmp != null) {
            count++;
            tmp = tmp.next;
        }
        return count;
    }
}
